<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/9
 * Time: 18:40
 */

namespace App\HttpController\V1;

use App\HttpController\Taoran\Functions\Publics;
use EasySwoole\EasySwoole\Config;
use App\Common\Checking;
use App\Common\Sms;
use App\Common\personal\Qrcode;
class Users extends Auth
{

    /**
     * 个人信息
     * @return bool
     */
    function userInfo(){
        $data=$this->db->where('id',$this->user->id)->getOne('users','id as user_id,uuid,headimg,nickname,mobile,pid,truename,sign,level,vip_expire_time,balance,lover');
        $p_user=$this->db->where('id',$data['pid'])->getOne('users','mobile');
        $data['invite']=$p_user['mobile'];
        $data['mate_count']=$this->db
            ->where('pid',$this->user->id)
            ->whereIn('lay',[1,2])
            ->count('users_position');
        if($data['headimg']!=null){
            $data['headimg']=QINIU_URL.$data['headimg'];
        }
        if($data['mobile']!=null){
            $data['mobile'] = Checking::replaceStar($data['mobile']);
        }
        if($data['invite']!=null){
            $data['invite'] = Checking::replaceStar($data['invite']);
        }
        return $this->writeJson(200,$data,'成功');
    }

    /**
     * 上传头像
     * @return bool
     */
    function uploadHead(){
        $image=$this->input('image');
        try {
            if ( empty( $img_file ) ) {
                return $this->writeJson( -202, null, '参数错误' );
            }

            $typeAll = ['image/jpg', 'image/jpeg', 'image/png'];
            $fileType = $img_file->getClientMediaType();
            if ( !in_array( $fileType, $typeAll ) ) {
                return $this->writeJson( -203, null, '图片格式错误' );
            }

            if ( $img_file->getSize() > 1024 * 1024 * 5 ) {
                return $this->writeJson( -204, null, '上传文件不可超过5M' );
            }

            $suffix = explode( "/", $fileType )[1] ?: 'png';

            $file_name = substr( hash( 'sha256', $this->user->id ), 5, 7 ) . date( 'YmdHis' ) . rand( 10000, 99999 ) . '.' . $suffix;
            $upload_dir = Config::getInstance()->getConf( 'UPLOAD_DIR' ) . DIRECTORY_SEPARATOR . date( "Ymd" ) . DIRECTORY_SEPARATOR;
            if ( !is_dir( $upload_dir ) ) {
                mkdir( $upload_dir );
            }
            $img_file->moveTo( $upload_dir . $file_name );
            /*$image = Image::open( $upload_dir . $file_name );
            $image->thumb( 500, 500 )->save( $upload_dir . $file_name );*/
            $this->db->where('id',$this->user->id)->update('users',['headimg'=>str_replace( EASYSWOOLE_ROOT, "", $upload_dir ) . $file_name]);
            return $this->writeJson( 200, API_URL.str_replace( EASYSWOOLE_ROOT, "", $upload_dir ) . $file_name, '上传成功' );
        } catch ( \Exception $exception ) {
            return $this->writeJson( -201, null, $exception->getMessage() );
        }
    }

    /**
     * 修改个人中心
     */
    function upUserInfo(){
        $param=$this->input('headimg,nickname,truename,sign');
        $param['headimg']=str_replace(QINIU_URL,null,$param['headimg']);

        if($param['truename']!=null||$param['truename']!=''){
            if(!preg_match('/^([\xe4-\xe9][\x80-\xbf]{2}){2,20}$/',$param['truename'])){
                return $this->writeJson(-202,null,'姓名格式错误');
            }
        }
        if(mb_strlen($param['nickname'],"utf-8")>8||mb_strlen($param['nickname'],"utf-8")<2){
            return $this->writeJson(-203,null,'请填写2~8位昵称');
        }
        if(mb_strlen($param['sign'],"utf-8")>22){
            return $this->writeJson(-204,null,'签名仅限22个字');
        }
        try{
            $this->db->where('id',$this->user->id)->update('users',$param);
            return $this->writeJson( 200, null, '成功');
        }catch (\Exception $e){
            return $this->writeJson( -201, null, $e->getMessage());
        }
    }

    /**
     * 是否设置支付密码
     */
    function isPayPassword(){
        $data=$this->db->where('id',$this->user->id)->getOne('users','pay_password');
        if($data['pay_password']==null){
            $data=0;
        }else{
            $data=1;
        }
        return $this->writeJson( 200, $data, '成功');
    }

    /**
     * 设置支付密码
     * @return bool
     */
    function setPW(){
        $param=$this->input('code,password,repassword,phone');
        if ( !Checking::keyIsExistence( ['code','password', 'repassword','phone'], $param ) ) {
            return $this->writeJson( -202, null, Checking::MESSAGE['keyIsExistence'] );
        }
        $sms_confirm = (new Sms)->confirmation($param['phone'],$param['code'],3,$this->db);
        if ( $sms_confirm['status'] != 1 ) {
            return $this->writeJson(-203,null,$sms_confirm['msg']);//验证码错误
        }
        if ( !Checking::transactionPwdRule( $param['password'] ) ) {
            return $this->writeJson( -204, null, Checking::MESSAGE['transactionPwdRule'] );
        }
        if ( $param['password'] != $param['repassword'] ) {
            return $this->writeJson( -205, null, '两次输入密码不一致' );
        }
        try{
            $this->db
                ->where('id',$this->user->id)
                ->update('users',['pay_password' => Checking::passwordHash($param['password'])]);
            return $this->writeJson( 200, null, '修改交易密码成功' );
        }catch (\Exception $e){
            return $this->writeJson( -201, null, $e->getMessage());
        }
    }

    /**
     * 提现
     */
    function return_cash(){
        $param=$this->input('money,type'); //1 支付宝  2微信  3银行卡
        if ( !Checking::keyIsExistence( ['money','type'], $param ) ) {
            return $this->writeJson( -202, null, Checking::MESSAGE['keyIsExistence'] );
        }
        if(!in_array($param['type'],[1,2,3])){
            return $this->writeJson( -203, null, '提现方式错误' );
        }
        $cash_start=$this->db->where('name','cash_start')->getValue('config','value');
        $cash_charge=$this->db->where('name','cash_charge')->getValue('config','value');
        $money=$param['money']-$param['money']*$cash_charge/100;
        if($param['money']<$cash_start){
            return $this->writeJson( -204, null, '最低'.$cash_start.'元起提' );
        }
        $balance=$this->db->where('id',$this->user->id)->getValue('users','balance');
        if($param['money']>$balance){
            return $this->writeJson( -205, null, '超过最大可提现金额' );
        }
        $this->db->startTransaction();
        switch ($param['type']){
            case 1:
                $payment_id=$this->db->where('user_id',$this->user->id)->where('type','alipay')->where('status','on')->getValue('payment','id');
                if(!$payment_id){
                    return $this->writeJson( -206, null, '账户未绑定，请先前往绑定' );
                }
                break;
            case 2:
                $payment_id=$this->db->where('user_id',$this->user->id)->where('type','wechat')->where('status','on')->getValue('payment','id');
                if(!$payment_id){
                    return $this->writeJson( -206, null, '账户未绑定，请先前往绑定' );
                }
                break;
            case 3:
                $payment_id=$this->db->where('user_id',$this->user->id)->where('type','bank')->where('status','on')->getValue('payment','id');
                if(!$payment_id){
                    return $this->writeJson( -206, null, '账户未绑定，请先前往绑定' );
                }
                break;
            default:
                return $this->writeJson( -206, null, '账户未绑定，请先前往绑定' );
        }
        try{
            $this->db->where('id',$this->user->id)->setDec('users','balance',$param['money']);
            $this->db->insert('return_cash',[
                'user_id'=>$this->user->id,
                'money'=>$money,
                'payment_id'=>$payment_id,
                'cash_charge'=>$cash_charge,
                'before_money'=>$param['money'],
                'pay_style'=>$param['type'],
                'create_time'=>date('YmdHis')
            ]);
            $this->db->insert('users_account_log',[
                'user_id'=>$this->user->id,
                'coin_type'=>'study',
                'type'=>7,
                'class'=>2,
                'money'=>$param['money'],
                'remark'=>'提现比例:'.$cash_charge/100,
                'createtime'=>date('YmdHis'),
                'before_money'=>$balance
            ]);
            $this->db->commit();
            return $this->writeJson( 200, null, '提现成功' );
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->writeJson( -201, null, '失败' );
        }

    }

    /**
     * 获取提现详情
     */
    function return_cash_detail(){
        $list=['cash_start'=>0,'cash_charge'=>0,'balance'=>0,'bank'=>0];
        $cash_start=$this->db->where('name','cash_start')->getValue('config','value');
        $cash_charge=$this->db->where('name','cash_charge')->getValue('config','value');
        $balance=$this->db->where('id',$this->user->id)->getValue('users','balance');
        $bank=$this->db->where('user_id',$this->user->id)->where('type','bank')->where('status','on')->has('payment');
        if($bank){
            $list['bank']=1;
        }
        if($cash_start){
            $list['cash_start']=$cash_start;
        }
        if($cash_charge){
            $list['cash_charge']=$cash_charge;
        }
        if($balance){
            $list['balance']=$balance;
        }
        return $this->writeJson(200,$list,'成功');
    }


    /**
     * 我的关注
     */
    function follow_list(){
        $page=$this->input('page') ?: 1;
        $page_size=10;
        $data=$this->db->where('user_id',$this->user->id)->get('users_follow',[($page-1)*$page_size,$page_size],'id,to_user_id,create_time');
        foreach ($data as $k=>&$v){
            $users=$this->db->where('id',$v['to_user_id'])->getOne('users','nickname,headimg');
            $v['headimg']=QINIU_URL.$users['headimg'];
            $v['nickname']=$users['nickname'];
            $v['count']=$this->db->where('to_user_id',$v['to_user_id'])->count('users_follow');
        }
        return $this->writeJson( 200, $data, '成功' );
    }

    /**
     * 分享邀请
     * @return bool
     */
    function qrcode(){
        $user_info = $this->db->where('id',$this->user->id)->getOne('users', 'uuid,mobile');//获取个人信息
        $nologo_code=$user_info['uuid'].'.png';
        $bgcode = 'Upload/img/codeBg.jpg';
        $path = 'Upload/qrcode/';//  todo
        $url =WEB_URL.'/visitors/register?uuid='.$user_info['uuid'];
        #引入包
        $object = new Qrcode();
        #容错级别
        $errorCorrectionLevel = 'G';
        #生成图片大小H
        $matrixPointSize = 5.1;
        #生成一个无logo二维码图片
        $object->png($url, $path . $nologo_code, $errorCorrectionLevel, $matrixPointSize, 0);
        $dst_path = $bgcode;  #底图  背景图
        $src_path = $path . $nologo_code; #二维码
        #创建图片的实例
        $dst = imagecreatefromstring(file_get_contents($dst_path));#背景
        $src = imagecreatefromstring(file_get_contents($src_path));#二维码
        #获取图片的宽高
        list($src_w, $src_h) = getimagesize($src_path);
        imagecopymerge($dst, $src, 426, 1055, 0, 0, $src_w, $src_h, 100);#二维码
        #生成图片  宽   高       类型
        list($dst_w, $dst_h, $dst_type) = getimagesize($dst_path);

        #判断一下图片的类型
        switch ($dst_type) {
            case 1:#GIF
//                header('Content-type: image/gif');
                imagejpeg($dst, $path . $nologo_code);
                break;
            case 2:#png
//                header('Content-type: image/png');
                imagepng($dst, $path . $nologo_code);
                break;
            case 3:#jpeg
//                header('Content-type: image/jpeg');
                imagejpeg($dst, $path . $nologo_code);
                break;
            default:
                break;
        }
        #将图片释放
        imagedestroy($dst);
        imagedestroy($src);
        $web_url=API_URL.'/'.$path . $nologo_code;
        return $this->writeJson( 200,$web_url , '成功' );

    }


}